'use strict';

const Controller = require('egg').Controller;
const fs = require('mz/fs');

const path = require("path");

class HomeController extends Controller {
  async index() {
    const { ctx,service } = this;
    // const ddmong=await service.getDocument.createdata();
      const ddmong=await ctx.model.Article.find({_id:"5dfdbccdd096e0e8c88f87e1"})
      await ctx.render('index.html',{cont:ddmong})
    // ctx.body="123";

  }
  async download() {
    const filePath=path.join(__dirname+"/../public/1566735254126.jpg")
    const { ctx } = this;
    ctx.attachment(filePath)
      ctx.set('Content-Type','application/octet-staream')
    ctx.body =fs.createReadStream(filePath);
  }
  async upload() {
      const { ctx } = this;
      // const fil =  ctx.request.files;
      // console.log('共 %d files', ctx.request.files.length);
      // for (const file of fil) {
      //     // 读取文件
      //     let files = fs.readFileSync(file.filepath) //files[0]表示获取第一个文件，若前端上传多个文件则可以遍历这个数组对象
      //     // 将文件存到指定位置
      //     fs.writeFileSync(path.join(this.config.baseDir, 'app/public', file.filename), files)
      //
      // }

      //strem方式
      const parts = ctx.multipart();
      let part;
      while ((part = await parts()) != null) {
          if (part.length) {
              // 处理其他参数
              console.log('field: ' + part[0]);
              console.log('value: ' + part[1]);
              console.log('valueTruncated: ' + part[2]);
              console.log('fieldnameTruncated: ' + part[3]);
          } else {
              if (!part.filename) {

                  continue;
              }
              let writePath = path.join(this.config.baseDir, 'app/public', part.filename)
              let writeStrem = fs.createWriteStream(writePath)
              await part.pipe(writeStrem)
          }
      }
      ctx.body = { code: 200, message: '上传完成', data:part.fields}
  }
}

module.exports = HomeController;
